<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "template".
 *
 * @property integer $id
 * @property string $name
 * @property string $content
 * @property integer $type
 * @property string $create_time
 * @property integer $status
 */
class Template extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'template';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name','keyword', 'content', 'type', 'status'], 'required'],
            [['keyword'], 'unique'],
            [['content'], 'string'],
            [['type', 'status'], 'integer'],
            [['create_time'], 'safe'],
            [['name', 'tpl_id'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => '标题',
            'keyword' => '关键词',
            'content' => '内容',
            'type' => '类型',
            'create_time' => '创建时间',
            'status' => '状态',
            'tpl_id' => '第三方模板id',
        ];
    }

    public static function itemAlias ($type, $code = NULL)
    {
        $_items = [
            'status' => [
                //''  =>'全部',
                '1' => "启用",              
                '2' => "停用",
            ],
            'type' => [
                //''  =>'状态',
                '1' => "短信",              
                '2' => "微信",
                               
            ],
         
        ];

        if (isset($code))
            return isset($_items[$type][$code]) ? $_items[$type][$code] : false;
        else
            return isset($_items[$type]) ? $_items[$type] : false;
    }

    /*
    * 保存前执行的操作
    */
    public function beforeSave($insert) {
        if (parent::beforeSave($insert)) {
            //是否是新添加
            if($this->isNewRecord) {
                $this->create_time = date("Y-m-d H:i:s", time());
              //  $this->update_time = date("Y-m-d H:i:s", time());
            }else{
                //$this->update_time = date("Y-m-d H:i:s", time());
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * @desc 根据关键字获取一个对象或者具体的值
     * @param string $keyword 关键词
     * @param string $field 指定获取的字段名
     * @return obj/string 返回对象或者字符串
     */
    public static function getValue ($keyword, $field='')
    {
        if (!$keyword)
            return false;
        $info = Template::find()->where(['keyword' => $keyword])->one();
        if (!$info)
            return false;

        if( !$field )
            return $info;
        else
            return $info->$field;
    }
}
